﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Web;

namespace Common
{
    public class FileComm
    {
        /// <summary>
        /// 写入文件内容，重新覆盖
        /// </summary>
        /// <param name="filenam">文件相对路径</param>
        /// <param name="content">需要写入的内容</param>
        public static void WriteHtml(string filenam, string content)
        {

            //指定要生成的HTML文件
            string fname = System.Web.HttpContext.Current.Server.MapPath(filenam);
            //创建文件信息对象
            FileInfo finfo = new FileInfo(fname);
            //以打开或者写入的形式创建文件流
            using (FileStream fs = new FileStream(fname, FileMode.Create))
            {
                //根据上面创建的文件流创建写数据流
                StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.GetEncoding("GB2312"));
                //把新的内容写到创建的HTML页面中
                sw.WriteLine(content);
                sw.Flush();
                sw.Close();
            }
        }

        /// <summary>
        /// 写文件  当文件不存时，则创建文件，并追加文件  调用示列：string Path = Server.MapPath("~/Log/Log.txt");  string Strings = "这是我写的内容啊"; EC.FileObj.WriteFile(Path,Strings);
        /// </summary>
        /// <param name="Path">文件路径</param>
        /// <param name="Strings">文件内容</param>
        public static void WriteFile(string Path, string Strings)
        {
            if (!System.IO.File.Exists(Path))
            {
                System.IO.FileStream f = System.IO.File.Create(Path);
                f.Close();
            }
            System.IO.StreamWriter f2 = new System.IO.StreamWriter(Path, true, System.Text.Encoding.GetEncoding("gb2312"));
            f2.WriteLine(Strings);
            f2.Close();
            f2.Dispose();
        }

        /// <summary>
        /// 将指定路径中的文件内容读出来 以字符串形式返回
        /// </summary>
        /// <param name="filenam">文件相对路径</param>
        /// <returns></returns>
        public static string ReadFiles(string filePath)
        {
            if (File.Exists(filePath))
            {
                //读取文本　
                StreamReader sr = new StreamReader(filePath, System.Text.Encoding.Default);
                string str = sr.ReadToEnd();
                sr.Close();
                return str;
            }
            else
                return "";
        }
        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="Path"></param>
        public static void FolderCreate(string Path)
        {
            // 判断目标目录是否存在如果不存在则新建之
            if (!Directory.Exists(Path))
                Directory.CreateDirectory(Path);
        }

        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="Path"></param>
        public static void FileCreate(string Path)
        {
            FileInfo CreateFile = new FileInfo(Path); //创建文件 
            if (!CreateFile.Exists)
            {
                FileStream FS = CreateFile.Create();
                FS.Close();
            }
        }

        /// <summary>
        /// 递归删除文件夹目录及文件
        /// </summary>
        /// <param name="dir"></param> 
        /// <returns></returns>
        public static void DeleteFolder(string dir)
        {
            if (Directory.Exists(dir)) //如果存在这个文件夹删除之 
            {
                foreach (string d in Directory.GetFileSystemEntries(dir))
                {
                    if (File.Exists(d))
                        File.Delete(d); //直接删除其中的文件                        
                    else
                        DeleteFolder(d); //递归删除子文件夹 
                }
                Directory.Delete(dir, true); //删除已空文件夹                 
            }
        }
        /// <summary>
        /// 删除目录下的所有文件
        /// </summary>
        /// <param name="strPath"></param>
        public static void DelAllFile(string strPath)
        {
            if (Directory.GetFiles(strPath).Length > 0)
            {
                foreach (string FileName in Directory.GetFiles(strPath))
                {
                    File.Delete(FileName);
                }

            }

        }
        /// <summary>
        /// 删除指定目录下的文件
        /// </summary>
        /// <param name="strPath"></param>
        public static void DeleteFile(string strPath)
        {
            if (File.Exists(strPath))
            {
                File.Delete(strPath);
            }
        }
        /// <summary>
        /// 指定文件夹下面的所有内容copy到目标文件夹下面
        /// </summary>
        /// <param name="srcPath">原始路径</param>
        /// <param name="aimPath">目标文件夹</param>
        public static void CopyDir(string srcPath, string aimPath)
        {
            try
            {
                // 检查目标目录是否以目录分割字符结束如果不是则添加之
                if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar)
                    aimPath += Path.DirectorySeparatorChar;
                // 判断目标目录是否存在如果不存在则新建之
                if (!Directory.Exists(aimPath))
                    Directory.CreateDirectory(aimPath);
                // 得到源目录的文件列表，该里面是包含文件以及目录路径的一个数组
                //如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
                //string[] fileList = Directory.GetFiles(srcPath);
                string[] fileList = Directory.GetFileSystemEntries(srcPath);
                //遍历所有的文件和目录
                foreach (string file in fileList)
                {
                    //先当作目录处理如果存在这个目录就递归Copy该目录下面的文件

                    if (Directory.Exists(file))
                        CopyDir(file, aimPath + Path.GetFileName(file));
                    //否则直接Copy文件
                    else
                        File.Copy(file, aimPath + Path.GetFileName(file), true);
                }
            }
            catch (Exception ee)
            {
                throw ee;
            }
        }
        /// <summary>
        /// 复制文件到指定目录并重命名
        /// </summary>
        /// <param name="oldPath"></param>
        /// <param name="newPath"></param>
        /// <param name="newFile"></param>
        public static void CopyFile(string oldPath, string newPath, string newFile)
        {
            try
            {
                if (!Directory.Exists(newPath))
                {
                    Directory.CreateDirectory(newPath);
                }
                File.Copy(oldPath, newPath + newFile, true);
            }
            catch (Exception ee)
            {
                throw ee;
            }
        }
        /// <summary>
        /// 获取指定文件详细属性
        /// </summary>
        /// <param name="filePath">文件详细路径</param>
        /// <returns></returns>
        public static string GetFileAttibe(string filePath)
        {
            string str = "";
            System.IO.FileInfo objFI = new System.IO.FileInfo(filePath);
            str += "详细路径:" + objFI.FullName + "<br/>文件名称:" + objFI.Name + "<br/>文件长度:" + objFI.Length.ToString() + "字节<br/>创建时间" + objFI.CreationTime.ToString() + "<br/>最后访问时间:" + objFI.LastAccessTime.ToString() + "<br/>修改时间:" + objFI.LastWriteTime.ToString() + "<br/>所在目录:" + objFI.DirectoryName + "<br/>扩展名:" + objFI.Extension;
            return str;
        }
        /// <summary>
        /// 把DataSet内容导出excel并返回客户端 
        /// </summary>
        /// <param name="dsData">数据集</param>
        /// <param name="strName">列名数组</param>
        /// <param name="strCaption">数据标题</param>
        /// <param name="strFileName">保存为的文件名</param>
        public static void DataToExcel(System.Data.DataSet dsData, string[] strName, string strCaption, string strFileName)
        {
            System.Data.DataTable dtData = dsData.Tables[0];
            System.Web.UI.WebControls.GridView dgExport = null;
            // 当前对话 
            System.Web.HttpContext curContext = System.Web.HttpContext.Current;
            // IO用于导出并返回excel文件 
            System.IO.StringWriter strWriter = null;
            System.Web.UI.HtmlTextWriter htmlWriter = null;

            if (dtData != null)
            {
                string attachment = "attachment; filename=" + System.Web.HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8) + ".xls";
                // 设置编码和附件格式 
                HttpResponse Response = HttpContext.Current.Response;
                Response.ClearContent();
                Response.AddHeader("content-disposition", attachment);
                //Response.ContentType = "application/ms-excel";
                Response.ContentType = "application/vnd.ms-excel";
                Response.ContentEncoding = System.Text.Encoding.UTF7;
                Response.Charset = "";

                // 导出excel文件 
                strWriter = new System.IO.StringWriter();
                htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);

                // 为了解决dgData中可能进行了分页的情况，需要重新定义一个无分页的DataGrid 
                dgExport = new System.Web.UI.WebControls.GridView();
                dgExport.Caption = strCaption;
                dgExport.RowStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Left;
                dgExport.HeaderStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Left;
                dgExport.HeaderStyle.Font.Bold = false;
                dgExport.DataSource = dtData.DefaultView;

                if (strName.Length > 0)
                {
                    int i;
                    for (i = 0; i < strName.Length; i++)
                    {
                        dtData.Columns[i].ColumnName = strName[i];
                    }
                }
                dgExport.AllowPaging = false;
                dgExport.DataBind();

                // 返回客户端 
                dgExport.RenderControl(htmlWriter);
                curContext.Response.Write(strWriter.ToString());
                curContext.Response.End();
            }
        }
    }
}